using System.Text.Json;

namespace SPI.AgentServer.Services.Export;

/// <summary>
/// 简化版图表服务 - 稳定可靠的基础实现
/// </summary>
public class SimpleChartService : IChartService
{
    private readonly ILogger<SimpleChartService> _logger;

    public SimpleChartService(ILogger<SimpleChartService> logger)
    {
        _logger = logger;
    }

    public async Task<ChartResult> GenerateChartAsync(object data)
    {
        return await Task.Run(() =>
        {
            try
            {
                // 尝试从数据中提取 columns 和 rows
                var dataType = data.GetType();
                var columnsProperty = dataType.GetProperty("columns");
                var rowsProperty = dataType.GetProperty("rows");

                if (columnsProperty == null || rowsProperty == null)
                {
                    return NoChart("数据格式不正确");
                }

                var columnsValue = columnsProperty.GetValue(data);
                var rowsValue = rowsProperty.GetValue(data);

                if (columnsValue is not IEnumerable<object> columns || 
                    rowsValue is not IEnumerable<object> rows)
                {
                    return NoChart("无法解析数据");
                }

                var columnList = columns.Select(c => c.ToString() ?? "").ToList();
                var rowList = rows.ToList();

                if (rowList.Count == 0 || rowList.Count > 100)
                {
                    return NoChart($"数据行数不适合图表: {rowList.Count}");
                }

                // 简单规则：取前2列，第1列作为标签，第2列作为数值
                if (columnList.Count < 2)
                {
                    return NoChart("列数不足");
                }

                var labels = new List<string>();
                var values = new List<double>();

                // 只取前20行
                foreach (var row in rowList.Take(20))
                {
                    var rowType = row.GetType();
                    var props = rowType.GetProperties()
                        .Where(p => p.GetIndexParameters().Length == 0)
                        .ToList();

                    if (props.Count < 2) continue;

                    try
                    {
                        // 第一个属性作为标签
                        var labelValue = props[0].GetValue(row);
                        labels.Add(labelValue?.ToString() ?? "");

                        // 第二个属性作为数值（尝试多个属性找到数值）
                        double numValue = 0;
                        bool foundNumber = false;

                        for (int i = 1; i < props.Count && !foundNumber; i++)
                        {
                            var val = props[i].GetValue(row);
                            if (val != null && double.TryParse(val.ToString(), out numValue))
                            {
                                foundNumber = true;
                            }
                        }

                        values.Add(numValue);
                    }
                    catch
                    {
                        labels.Add("");
                        values.Add(0);
                    }
                }

                if (labels.Count == 0)
                {
                    return NoChart("无有效数据");
                }

                // 生成简单的横向柱状图
                var config = new
                {
                    title = new { text = $"数据统计 (前{labels.Count}条)", left = "center" },
                    tooltip = new { trigger = "axis" },
                    grid = new { left = "15%", right = "10%", bottom = "3%", top = "10%", containLabel = true },
                    xAxis = new { type = "value" },
                    yAxis = new { 
                        type = "category", 
                        data = labels.ToArray(),
                        axisLabel = new { fontSize = 10 }
                    },
                    series = new[]
                    {
                        new
                        {
                            type = "bar",
                            data = values.ToArray(),
                            itemStyle = new { color = "#667eea" }
                        }
                    }
                };

                return new ChartResult
                {
                    ChartType = "bar",
                    Config = JsonSerializer.Serialize(config),
                    Summary = $"生成柱状图，包含 {labels.Count} 条数据"
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "图表生成失败");
                return NoChart(ex.Message);
            }
        });
    }

    private ChartResult NoChart(string reason)
    {
        _logger.LogInformation("不生成图表: {Reason}", reason);
        return new ChartResult
        {
            ChartType = "none",
            Summary = $"未生成图表: {reason}"
        };
    }
}

